<template>
  <view class="meter-overview-container">
    <!-- 页面头部 -->
    <view class="header-bar">
      <view class="page-title">
        水表流量概览
        <text class="current-date">({{ dayjs().format('YYYY-MM-DD') }})</text>
      </view>
      <view class="operate-btns">
        <button
          class="btn primary"
          :loading="loading"
          @click="handleRefresh"
        >
          🔄 刷新
        </button>
        <button class="btn" @click="handlePrint">🖨️ 打印</button>
      </view>
    </view>

    <!-- 加载中 -->
    <uni-load-more
      v-if="loading"
      status="loading"
      :content-text="{ contentrefresh: '加载中...' }"
    ></uni-load-more>

    <!-- 卡片容器 -->
    <view class="card-grid" v-else>
      <uni-card
        v-for="element in elementList"
        :key="element.id"
        :title="element.elemName || '未知水表'"
		class="meter-card"
      >
        <view class="data-item">
          <text class="data-label">昨日用水：</text>
          <text class="data-value">
            {{ getAnalyseData(element.id)?.todayUsage || '-' }} 吨
          </text>
        </view>

        <view class="data-item">
          <text class="data-label">最小流量：</text>
          <text class="data-value">
            {{ getAnalyseData(element.id)?.todayMinVal || '-' }} 吨/小时
          </text>
        </view>

        <view class="data-item">
          <text class="data-label">更新时间：</text>
          <text class="data-value">
            {{ formatDate(getAnalyseData(element.id)?.recordTime) }}
          </text>
        </view>

        <view class="data-item">
          <text class="data-label">告警状态：</text>
          <text class="data-value warn-count">
            {{ warnCountMap[element.id] || 0 }} 次告警
          </text>
        </view>
      </uni-card>

      <view class="empty-tip" v-if="elementList.length === 0">
        暂无水表数据
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import dayjs from 'dayjs'

// 模拟接口（你实际项目用自己的 API）
import { listElement } from '@/api/water/element'
import { listMeterAnalyse } from '@/api/water/meterAnalyse'
import { listMeterWarn } from '@/api/water/meterWarn'

const elementList = ref([])
const meterAnalyseMap = ref({})
const warnCountMap = ref({})
const loading = ref(false)

// 获取昨天日期
const getYesterdayDate = () => dayjs().subtract(1, 'day').format('YYYY-MM-DD')

// 日期格式化
const formatDate = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (!date || !dayjs(date).isValid()) return ''
  return dayjs(date).format(format)
}

// 分页获取所有水表
const getAllElements = async () => {
  const allElements = []
  const pageSize = 20
  let pageNum = 1
  let total = 0

  do {
    try {
      const res = await listElement({ pageNum, pageSize })
      if (pageNum === 1) total = res.total || 0
      if (res.rows?.length) allElements.push(...res.rows)
      pageNum++
    } catch (error) {
      uni.showToast({ title: `第${pageNum}页加载失败`, icon: 'error' })
      break
    }
  } while (allElements.length < total)

  return allElements
}

// 主加载函数
const loadAllData = async () => {
  loading.value = true
  try {
    const allElements = await getAllElements()
    elementList.value = allElements
    if (elementList.value.length === 0) return

    const yesterday = getYesterdayDate()
    const analyseResList = await Promise.all(
      elementList.value.map(el =>
        listMeterAnalyse({ meterId: el.id, startTime: yesterday, endTime: yesterday })
      )
    )

    analyseResList.forEach((res, i) => {
      const el = elementList.value[i]
      meterAnalyseMap.value[el.id] = res.rows?.[0] || null
    })

    const warnResList = await Promise.all(
      elementList.value.map(el => listMeterWarn({ meterId: el.id }))
    )
    warnResList.forEach((res, i) => {
      const el = elementList.value[i]
      warnCountMap.value[el.id] = res.rows?.length || 0
    })
  } catch (error) {
    console.error(error)
    uni.showToast({ title: '加载失败', icon: 'error' })
  } finally {
    loading.value = false
  }
}

const getAnalyseData = id => meterAnalyseMap.value[id] || null

const handleRefresh = () => {
  meterAnalyseMap.value = {}
  warnCountMap.value = {}
  loadAllData()
}

const handlePrint = () => {
  uni.showToast({ title: '当前平台不支持打印', icon: 'none' })
}

onMounted(loadAllData)
</script>

<style scoped>
.meter-overview-container {
  padding: 20rpx;
  background-color: #f8f9fa;
  min-height: 100vh;
}
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}
.page-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
}
.current-date {
  font-size: 26rpx;
  color: #888;
  margin-left: 10rpx;
}
.operate-btns {
  display: flex;
  gap: 10rpx;
}
.btn {
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  border: none;
  background-color: #e5e7eb;
  color: #333;
}
.btn.primary {
  background-color: #007aff;
  color: #fff;
}
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(600rpx, 1fr));
  gap: 16rpx;
  padding: 8rpx;
  box-sizing: border-box;
}
/* 超过1200px时显示2列 */
/* @media (min-width: 600px) {
  .card-grid {
    grid-template-columns: repeat(2, 1fr);
  }
} */

/* 超过1800px时显示3列 */
/* @media (min-width: 1000px) {
  .card-grid {
    grid-template-columns: repeat(3, 1fr);
  }
} */
.meter-card {
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.meter-card:hover {
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
}
.data-item {
  display: flex;
  justify-content: space-between;
  padding: 6rpx 0;
  font-size: 26rpx;
}
.data-label {
  color: #6b7280;
}
.data-value {
  color: #111;
  font-weight: 500;
}
.warn-count {
  color: #dc2626;
}
.empty-tip {
  width: 100%;
  text-align: center;
  color: #999;
  padding: 40rpx 0;
  font-size: 28rpx;
}
</style>
